function getToken() {
    var token = localStorage.getItem("token") || "";
    if(token != "") {
        token = "Bearer " + token.substr(1, token.length-2);
    }
    return token;
}

function getUserInfo() {
    return JSON.parse(localStorage.getItem("userInfo")) || "";
}

function getClientId() {
    return localStorage.getItem("ClientId") || "";
}

function clearSession() {
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
}

function showLogin() {
    window.location.href = "/fastcms";
}

function showPayWin() {
    $("#payQrcodeDiv").show();
}

function hidePayWin() {
    $("#payQrcodeDiv").hide();
}

function submitForm(formId, rules, messages, okFunction, failFunction) {
    $("#" + formId).validate({
        rules: rules,
        messages: messages,
        errorElement: 'span',
        errorPlacement: function (error, element) {
            error.addClass('invalid-feedback');
            element.closest('.form-group').append(error);
        },
        highlight: function (element, errorClass, validClass) {
            $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
            $(element).removeClass('is-invalid');
        },
        submitHandler: function(form) {

            var formData = new FormData($(form)[0]);

            ajaxPost($(form).attr("action"), formData, okFunction, failFunction);

            return false;
        }
    });
}

function ajaxGet(url, okFunction, failFunction, needLogin) {
    if (url == null || "" == url) {
        alert("url 不能为空 ");
        return
    }

    okFunction = okFunction || function (result) {};

    failFunction = failFunction || function (result) {
        alert(result.message);
    };

    needLogin = needLogin === undefined ? true : false;

    $.ajax({
        url: url,
        type: "get",
        //不使用缓存
        cache: false,
        processData: false,
        beforeSend: function( xhr ) {
            xhr.setRequestHeader("Authorization", getToken());
            xhr.setRequestHeader("ClientId", getClientId());
        },
        success: function (result) {
            if(result.code && result.code != 200) {
                failFunction(result);
            }else {
                okFunction(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if(xhr.status == 403) {
                alert("403 forbid")
            } else if(xhr.status == 401) {
                clearSession();
                if(needLogin == true) {
                    showLogin();
                }
            } else {
                alert("unknow status");
            }
        },
        complete: function (resp) {

        }
    });

}

function ajaxGetWithoutLogin(url, okFunction) {
    ajaxGet(url, okFunction, function(){}, true)
}

function ajaxPost(url, data, okFunction, failFunction) {
    if (url == null || "" == url) {
        alert("url 不能为空 ");
        return
    }

    okFunction = okFunction || function (result) {};

    failFunction = failFunction || function (result) {
        alert(result.message);
    };

    $.ajax({
        url: url,
        type: "post",
        cache: false,
        processData: false,
        contentType: false,
        data: data,
        beforeSend: function( xhr ) {
            xhr.setRequestHeader("Authorization", getToken());
            xhr.setRequestHeader("ClientId", getClientId());
        },
        success: function (result) {
            if(result.code != 200) {
                failFunction(result);
            }else {
                okFunction(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if(xhr.status == 403) {
                alert("403 forbid")
            } else if(xhr.status == 401) {
                clearSession();
                showLogin();
            } else {
                alert("unknow status");
            }
        },
        complete: function (resp) {

        }
    });

}

function ajaxJsonPost(url, data, okFunction, failFunction) {
    if (url == null || "" == url) {
        alert("url 不能为空 ");
        return
    }

    okFunction = okFunction || function (result) {};

    failFunction = failFunction || function (result) {
        alert(result.message);
    };

    $.ajax({
        url: url,
        type: "post",
        cache: false,
        processData: false,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        data: data,
        beforeSend: function( xhr ) {
            xhr.setRequestHeader("Authorization", getToken());
            xhr.setRequestHeader("ClientId", getClientId());
        },
        success: function (result) {
            if(result.code != 200) {
                failFunction(result);
            }else {
                okFunction(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
            if(xhr.status == 403) {
                alert("403 forbid")
            } else if(xhr.status == 401) {
                clearSession();
                showLogin();
            } else {
                alert("unknow status");
            }
        },
        complete: function (resp) {

        }
    });

}

function getCaptcha(imageId) {
    ajaxGet("/fastcms/api/admin/captcha", function (res) {
        $("#"+imageId).attr("src", res.data.image);
        localStorage.setItem("ClientId", res.data.codeUuid);
    })
}

function initUserInfo() {
    if(getToken() != "") {
        var userInfo = getUserInfo();
        $(".logged").show();
        $(".user-login").hide();
        $(".logged").children(":first").children(":first").attr("src", userInfo.photo);
        $(".logged").children(":first").find("span").text(userInfo.username);
    } else {
        $(".logged").hide();
    }
}

$(function () {
    initUserInfo();

    /**
     * 登录
     */
    submitForm("loginForm", {
        username: { required: true },
        password: { required: true }
    },{
        username: { required: "请输入账号" },
        password: { required: "请输入密码" }
    }, function (res) {
        var userInfos = {
            username: res.data.username,
            photo: res.data.headImg === null ? '/header.jpg' : res.data.headImg,
            time: new Date().getTime(),
            hasRole: res.data.hasRole,
            version: res.data.version,
            userType: res.data.userType
        };
        // 存储 token 到浏览器缓存
        localStorage.setItem('token', '"' + res.data.token + '"');
        localStorage.setItem('tokenTtl', res.data.tokenTtl);
        // 存储用户信息到浏览器缓存
        localStorage.setItem('userInfo', JSON.stringify(userInfos));
        initUserInfo();
    }, function (result) {
        alert(result.message);
        getCaptcha("loginCaptcha");
    })

    var toggleIcon = document.querySelectorAll('.menu-toggle-btn ul')
    toggleIcon.forEach((element) =>{
        element.addEventListener('click', () =>{
            document.getElementById("menu-login-div").classList.add("show-sidebar");
            getCaptcha("loginCaptcha");
        })
    })

    $("#loginCaptcha").click(function () {
        getCaptcha("loginCaptcha")
    })

    $("#mobileLoginBtn").click(function () {
        showLogin();
    })

});
